#!/usr/bin/env python2.6

# test svn version

import os, re, urllib, urllib2
from time import sleep, ctime
from sys import exit, argv

class proxyfinder(object):
    def __init__(self, servers=(), ip='', hostip=''):
        self.servers = servers
        self.ip = ip
        self.hostip = hostip

    def clear(self):
        if os.name in ['nt', 'win32', 'dos']:
            os.system('cls')
        else:
            os.system('clear')


    def title(self):
        self.clear()
        skip = '#\t\t\t\t\t\t #'
        print '#'*50
        print skip
        print skip
        print '#\t    *************************\t\t #'
        print skip
        print '#\t    PROXY DIGGER Beta Version\t\t #'
        print skip
        print '#\t    *************************\t\t #'
        print skip
        print skip
        print '#\t            DEVELOPERS      \t\t #'
        print skip
        print '#\t  Irenicus, LeXeL, S3my0n, Norph\t #'
        print skip
        print '#'*50+'\n\n'
        lt = ctime()
        print '[+] Starting PROXY DIGGER at %s\n' %(lt)
        sleep(1)


    def parser(self):  

        # This is the core function of our program,                       
        # Try to introduce sets module in order to remove duplicates
        # Also use shelve module to keep persistent data &
        # Create another function making use of sys.argv to
        # store grabbed proxies if a user specifies a file. 
        # But first create a custom filter function
        # to sort data according to country & anonymity level of proxy
        # After the above has been done, create Live Version to automatically
        # grab proxies on the go.

        ua = 'Mozilla/5.0 (X11; U; Linux i686; en-US) Chrome/6.0.407.0'
        req = urllib2.Request('http://www.ip-adress.com/proxy_list/')
        req.add_header('User-Agent', ua)

        print '\n', '#'*75
        print '\n[*] Connecting to Server...\n'
        print '#'*75, '\n\n'

        try:
            source = (urllib2.urlopen(req)).read()    
        except (KeyboardInterrupt, BaseException):
            print '[-] Error Occured!'
            print '[*] Either System is Offline'
            print '[*] Or Force Quit was Attempted'
            sleep(2)
            exit(1)

        pattern1 = re.compile(r'<td>(\d+\.\d+\.\d+\.\d+\:\d+)</td>\s+<td>(\w+)</td>\s+<td>\s+<img src="\S+">\s+([A-Za-z ]*)\s+</td>')
        pattern2 = re.compile(r'<td>(\d+\.\d+\.\d+\.\d+\:\d+)</td>\s+<td>(\w+)</td>\s+<td>\s+(\w+)\s+</td>')
        search1 = pattern1.findall(source)  # search1 parses all Countries except Unknown/Unidentified ones
        search2 = pattern2.findall(source) # search2 parses only Unknown/Unidentified Countries
        data = search1+search2  # data combines the 2 searches
        temp = ()   # temp was created to unpack the tuple temporarily for sorting
        master_data = []    # master_data  is a list that will contain all data, sorted Country wise

        for i in data:
            temp = (i[2], i[1], i[0])
            master_data.append(temp)

        master_data.sort()

        print 'Country:\t\t Anonymity Level:\tProxy-Address:'
        print '======= \t\t =============== \t=============\n'

        for i in master_data:
            print '%s%s%s' % (i[0].ljust(25, ' '), i[1].ljust(23, ' '), i[2])

        print '\n'
        print '*'*75
        print '[+] Total Proxies Found: %s' % (len(master_data))
        print '-'*75

        self.waste()


    def whois_lookup(self):     # This function does WHOIS Query & it parses data
                                # from "proxies.com.ar" which could have been avoided
        self.clear()            # but it doesn't make much of a difference as long that
        self.validator()        # site is still up

        get = 'http://www.proxys.com.ar/index.php?act=whois&ip=%s' % (self.ip)
        
        try:
            source = (urllib2.urlopen(get)).read()
        except(KeyboardInterrupt, BaseException):
            print '[-] Error Occured!'
            print '[*] Either System is Offline'
            print '[*] Or Force Quit was Attempted'
            sleep(2)
            exit(1)
                                    
        pat = re.compile(r'<br />([\s|\w|\W]+)<br />\s+</td></tr>')
        whois = pat.findall(source)

        for i in whois:
            print i.replace('<br />', '')

        self.waste()


    def validator(self):    # This is a handy all in one function to validate IP Address
        while True:         # Note that this version now correcty validates IP for use
            try:            # in other functions
                self.ip = (raw_input('\nPlease Enter IP Address: ')).strip()
            except(KeyboardInterrupt):
                print '\n[!] Aborting..'
                sleep(2)
                exit(1)

            pat = re.compile(r'(\d+)\.(\d+)\.(\d+)\.(\d+)')
            valid = pat.findall(self.ip)

            if (valid):
                print '\n[+] Basic IP Validation Passsed'
                sleep(1)
                first = int(valid[0][0])
                second = int(valid[0][1])
                third = int(valid[0][2])
                fourth = int(valid[0][3])

                if (first <= 255 and second <= 255 and third <= 255 and fourth <= 255):
                    print '\n[+] Advanced IP Validation Passed'
                    sleep(1)
                    break
                else:
                    print '\n[-] Advanced IP Validation Failed! Try Again..'
                    sleep(1)
                    self.clear()
            else:
                print '\n[-] Invalid Input! Try Again..'
                sleep(1)
                self.clear()


    def proxy_tester(self):     # Limited Version of Proxy Tester to individually test proxies
        self.clear()            # Work on expanding this function to Mass Test Proxies
                                # & at the same time try to make it more efficient & light-weight
        print '#'*50
        print '\n\n\tProxy Tester [Limited Edition]\n\n'
        print '#'*50, '\n\n'

        ua = 'Mozilla/5.0 (X11; U; Linux i686; en-US) Chrome/6.0.407.0'               
        req = urllib2.Request('http://www.ip-adress.com/Proxy_Checker/')
        req.add_header('User-Agent', ua)
        data = {}

        self.validator()

        data["proxy"] = self.ip
        data["submit"] = "Check this Proxy"

        values = urllib.urlencode(data)

        try:
            source = (urllib2.urlopen(req, values)).read()
        except(KeyboardInterrupt, BaseException):
            print '[-] Error Occured!'
            print '[*] Either System is Offline'
            print '[*] Or Force Quit was Attempted'
            sleep(2)
            exit(1)

        pattern1 = re.compile('<a href="/Proxy_Details/(\d+\.\d+\.\d+\.\d+:\d+):([\w\s]*)">')
        page = pattern1.findall(source)

        print '\n\n'
        print '*'*50, '\n'

        if page:
            for i in page:
                print '[*] IP %s is Working & is %s ' % (i[0], i[1])
        else:
            print '[!] IP %s is not a Working Proxy' % (self.ip)

        print '\n', '-'*50
        self.waste()


    def get_host_ip(self):  # This function is initiated at program startup
                            # to automatically display User External IP
        
        url = 'http://www.whatismyip.com/automation/n09230945.asp'

        try:
            source = (urllib.urlopen(url)).read()
        except(BaseException):
            self.hostip = 'Could not lookup your IP'
            pass
        else:
            self.hostip = source
            return self.hostip

        
    def ip_lookup(self):    # Simple Hostname Lookup Tool,
                            # This can be expanded if needed to
        data = {}           # allow user to view host name of proxies
                            # that are grabbed in the core function
        print '#'*50        # but can be quite resource hungry & bandwidth consuming.
        print '\n\t    SIMPLE HOST LOOK-UP TOOL\n'
        print '#'*50, '\n'

        self.validator()
        
        data['IP'] = self.ip
        data['HL'] = 'Host Lookup'
        
        values = urllib.urlencode(data)
        source = (urllib.urlopen('http://www.whatismyip.com/tools/host-name-lookup.asp', values)).read()
        pattern = re.compile(r'<br /><br />(.*)<br /><br />')

        page = pattern.findall(source)

        for i in page:
            page = i.replace('</font>', '')

        print '\n', '*'*50
        print '\nHost Name: %s\n' % (page)
        print '-'*50
        self.waste()


    def waste(self):    # This function takes in dump value in order to bring user to Main Menu
        try:            # Create a cleanup function to automatically perform memory cleanup when
            trash = raw_input('\n\n[*] Press Enter To Return To Main Menu') # user quits or due to
        except(KeyboardInterrupt):                                          # Keyboard Interrupt.
            print '\n\n[!] Force Quitting..'
            sleep(1)
            exit(1)


    def roll_credits(self):     # This function provides credits screen when user Quits
        self.clear()            # If you want to give thanks to someone special then add it here :-]
        print '#'*75
        print '\n\t\tPROXY DIGGER Beta Version'
        print '\n', '#'*75
        print '\nDevelopers: Irenicus, LeXeL, S3my0n, Norph'
        print '-'*75
        print 'Special Thanks To:\n\nMaXe [InterN0T Founder] "For his on going Support & Encouragement."'
        print 'YipyIP "For sharing his Python & Web related Knowledge"'
        print '='*75


    def select(self):
        print '#'*50
        print '\nMake Your Choice:\n'
        print '#'*50
        print '\n1)Un-Earth Proxies\n2)Proxy Tester (Limited Edition)\n3)WHOIS Look-Up\n4)Hostname Look-Up\n5)Exit\n'
        print '*'*50
        print 'Your External IP: %s' % (self.hostip)
        print '*'*50


    def main(self):     # Simple engine, improve it later once all the final
        self.title()    # modifications have been done.
        self.get_host_ip()
        while True:
            self.clear()
            self.select()
            try:
                choice = raw_input('\nYou Selected: ')
            except(KeyboardInterrupt):
                print '\n\n[!] Force Quitting..'
                sleep(1)
                exit(1)            
            if (choice in '12345'):
                if (choice == '1'):
                    self.clear()
                    self.parser()
                elif (choice == '2'):
                    self.proxy_tester()
                elif (choice == '3'):
                    self.clear()
                    self.whois_lookup()
                elif (choice == '4'):
                    self.clear()
                    self.ip_lookup()
                elif (choice == '5'):
                    self.roll_credits()
                    sleep(4)
                    exit(0)
            else:
                print '\n[-] Invalid Input! Try Again..'
                sleep(2)
                self.clear()



if __name__ == '__main__':
    proxy = proxyfinder()
    proxy.main()
